<template>
  <NModal v-model:show="visible" :title="title" :mask-closable="false" transform-origin="center" preset="card" @after-leave="closeDrawer" class="w-800px">
    <NScrollbar class="h-300px pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
        <NGrid responsive="screen" item-responsive>
          <NFormItemGi span="24 m:12" label="选择组织" path="orgId">
            <NTreeSelect v-model:value="model.orgId" label-field="name" key-field="id" :options="treeOptions"
                         placeholder="请选择所属组织" default-expand-all clearable/>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="角色名称" path="name">
            <NInput v-model:value="model.name" placeholder="请输入职位名称" clearable/>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="分类" path="category">
            <NSelect v-model:value="model.category" :options="roleCategoryOptions" placeholder="请选择分类" clearable/>
          </NFormItemGi>

          <NFormItemGi span="24 m:12" label="排序" path="sortCode">
            <NInputNumber class="w-100%" v-model:value="model.sortCode" placeholder="请输入排序" clearable/>
          </NFormItemGi>

        </NGrid>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">取消</NButton>
        <NButton type="primary" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<script setup lang="ts">
defineOptions({
  name: 'RoleEditModal'
});
import {reactive, toRefs,watch,computed} from "vue";
import {useFormRules, useNaiveForm} from '@/hooks/common/form';
import { roleCategoryOptions } from '@/constants/common';
import {orgSelectTree} from '@/service/api/org-api';
import {roleDetail} from '@/service/api/role-api'

export type OperateType = NaiveUI.TableOperateType;
const {formRef, validate, restoreValidation} = useNaiveForm();
const {defaultRequiredRule} = useFormRules();

interface Props {
  // 操作类型
  operateType: OperateType;
  // 编辑职位的数据
  rowData?: number;
}
interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const props = defineProps<Props>();
const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: '新增角色',
    edit: '编辑角色'
  };
  return titles[props.operateType];
});

const state = reactive({
  treeOptions: [] as Api.SystemManage.OrgTreeType[],
})
// 转为ref后解构
const {treeOptions} = {...toRefs(state)};
// 监听打开窗口时，逻辑处理
watch(visible, () => {
  if (visible.value) {
    // 清空表单
    Object.assign(model, createDefaultModel());
    // 获取组织选择树的数据
    getOrgSelectTree()
    if (props.operateType === 'edit' && props.rowData) {
      // 查询职位详情
      getPositionDetail();
    }
    restoreValidation();
  }
});
// form表单字段
type Model = Pick<Api.SystemManage.RoleInfo, 'orgId' | 'name' | 'code' | 'category' | 'sortCode'>;
const model: Model = reactive(createDefaultModel());
function createDefaultModel(): Model {
  return {
    orgId: null,
    name: '',
    code: '',
    category: null,
    sortCode:99
  }
}
// 排除非必填
type RuleKey = Exclude<keyof Model,  'code'>;
// 必填项
const rules: Record<RuleKey, App.Global.FormRule> = {
  orgId: defaultRequiredRule,
  name: defaultRequiredRule,
  sortCode:defaultRequiredRule,
  category: defaultRequiredRule
};

// 获取组织选择树的数据
async function getOrgSelectTree(){
  const {data} = await orgSelectTree()
  if (Array.isArray(data)) {
    state.treeOptions = data
  }
}

// 查询职位详情
async function getPositionDetail() {
  if (props.rowData != undefined) {
    const {data} = await roleDetail(props.rowData)
    Object.assign(model, data);
  }
}

// 取消、关闭弹框
function closeDrawer() {
  visible.value = false;
}

// 提交
async function handleSubmit() {
  // 必填项校验
  await validate();
  const params = getSubmitParams();
  console.log('params: ', params);
  // request
  window.$message?.success('操作成功');
  // 取消、关闭弹框
  closeDrawer();
  // 调用父组件事件
  emit('submitted');
}

function getSubmitParams() {
  const {...params} = model;
  return params;
}
</script>

<style scoped>

</style>
